//
//  AppDelegate.swift
//  weibo
//
//  Created by huxuedong on 15/12/5.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    //创建观察者
    var observer: NSObjectProtocol?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = HXDUserAccountViewModel.shareInstance.userLogin ? defatulRootViewController() : HXDMainViewController()
        window?.makeKeyAndVisible()
        //[weak self]解除循环引用
        observer = NSNotificationCenter.defaultCenter().addObserverForName("switchVC", object: nil, queue: nil, usingBlock: {[weak self](notification) -> Void in
            if notification.object is HXDWebLoginViewController {
                self?.window?.rootViewController = HXDWelcomeViewController()
            } else {
                self?.window?.rootViewController = HXDMainViewController()
            }
        })
        return true
    }
    
    private func defatulRootViewController() -> UIViewController {
        if hasNewVersion() {
            return HXDNewfeatureViewController()
        } else {
            return HXDWelcomeViewController()
        }
    }
    
    //判断是否有新版本
    private func hasNewVersion() -> Bool {
        let versionKey = "versionKey"
        //获取本地保存的版本号（旧）
        let localVersion = NSUserDefaults.standardUserDefaults().stringForKey(versionKey)
        //获取当前app的版本号（新）
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        //把当前app的版本号（新）保存到本地
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey)
        //当前app版本号大于或等于本地版本号（OrderedAscending：升序，OrderedDescending：降序）
        if let local = localVersion where currentVersion.compare(local) != NSComparisonResult.OrderedDescending {
            return false
        }
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(observer!)
    }

}

